{% extends "base.html" %}

{% load static %}
{% block css %}
    <link rel="stylesheet" href="{% static 'css/account.css' %}">
{% endblock %}

{% block title %}
    用户登录
{% endblock %}

{% block content %}
    <div class="account">
        <h1 class="title">登录</h1>
        <form action="" id="loginform">
            {% csrf_token %}
            {% for foo in forms_obj %}
                <div class="form-group">
                    <label for="{{ foo.auto_id }}">{{ foo.label }}</label>
                    {# <input type="text" class="form-control" id="{{ foo.auto_id }}">#}
                    {{ foo }}
                    <span style="color: red" class="pull-right error-msg">{{ foo.errors.0 }}</span>
                </div>
            {% endfor %}
            <!--下面input标签的type类型必须为button，不能写成subbmit，因为submit会直接提交表单-->
            <input type="button" class="btn btn-primary pull-left" value="登录" id="commit">
        </form>
    </div>
{% endblock %}

{% block js %}
    <script>
        $(function () {
            userLogin();
            removeError();

        })

        // 登录
        function userLogin() {
            var loginUrl = '{% url 'user:user_login' %}'
            var indexUrl = "{% url 'index' %}"
            var FormDataObj = new FormData
            $('#commit').click(function () {
                $('.error-msg').empty()
                {#console.log($('#loginform').serializeArray())#}
                $.each($('#loginform').serializeArray(), function (index, obj) {
                    FormDataObj.append(obj.name, obj.value)
                })
                $.ajax({
                    url: loginUrl,
                    type: 'post',
                    data: FormDataObj,
                    contentType: false,  <!--不使用任何编码格式-->
                    processData: false,  <!--浏览器不对数据做处理-->
                    success: function (args) {
                        if (args.status) {
                            window.location.href = indexUrl
                        } else {
                            $.each(args.msg, function (index, obj) {
                                console.log(index, obj)  // username  ['用户名不能为空']
                                let targetId = '#id_' + index
                                $(targetId).next().text(obj[0]).parent().addClass('has-error')
                            })
                        }
                    }
                })
            })
        }

        // 给所有的input框绑定获取焦点事件
        function removeError() {
            $('input').focus(function () {
                $(this).next().text('').parent().removeClass('has-error')
            })
        }
    </script>
{% endblock %}